package com.ccp.dev.core.basic.table.colmap;

import com.ccp.dev.core.basic.table.ColumnModel;
import com.ccp.dev.core.util.StringUtil;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * postgreSql 列的元数据到columnmodel的映射。
 * 用于从数据库元数据读取到列对象。
 * @author ray
 *
 */
public class PostgreSqlColumnMap implements RowMapper<ColumnModel> {


	@Override
    public ColumnModel mapRow(ResultSet rs, int row) throws SQLException {
		ColumnModel column=new ColumnModel();

		String name=rs.getString("column_name");
		String is_nullable=rs.getString("is_nullable");
		String data_type=rs.getString("data_type");
		String length=rs.getString("length");
		String precisions=rs.getString("precisions");
		String scale=rs.getString("scale");
		String table_name=rs.getString("table_name");
		int iLength;
		try{
			iLength= StringUtil.isEmpty(length)?0:Integer.parseInt(length);
		}catch (NumberFormatException e) {
			iLength=0;
		}
		int iPrecisions=StringUtil.isEmpty(precisions)?0:Integer.parseInt(precisions);
		int iScale=StringUtil.isEmpty(scale)?0:Integer.parseInt(scale);

		column.setName(name);
		column.setTableName(table_name);
		column.setComment(name);
		column.setIsPk(false);
		boolean isNull=is_nullable.equals("YES");
		column.setIsNull(isNull);
		setType(data_type,iLength,iPrecisions,iScale,column);
		return column;
	}
	
	/**
	 * 设置列类型。
	 * @param dbtype	数据库类型
	 * @param length	字符串长度
	 * @param precision	整数位
	 * @param scale		小数位
	 * @param column	列对象
	 */
	private void setType(String dbtype,int length,int precision,int scale,ColumnModel column)
	{
		if(dbtype.toLowerCase().indexOf("CHAR".toLowerCase())>-1){
			column.setColumnType(ColumnModel.COLUMNTYPE_VARCHAR);
			column.setCharLen(length);
			return;
		}
		if(dbtype.equalsIgnoreCase( "NUMERIC")|| dbtype.equalsIgnoreCase("DECIMAL")){
			column.setColumnType(ColumnModel.COLUMNTYPE_NUMBER);
			column.setIntLen(precision-scale);
			column.setDecimalLen(scale);
			int i= precision-scale;
			if(i==0 && scale==0){
				column.setIntLen(38);
			}
			return;
		}
		if(dbtype.equalsIgnoreCase( "INTEGER")){
			column.setColumnType(ColumnModel.COLUMNTYPE_NUMBER);
			column.setIntLen(10);
			column.setDecimalLen(0);
			return;
		}
		if(dbtype.equalsIgnoreCase("DATE") || dbtype.toLowerCase().indexOf("TIMESTAMP".toLowerCase())!=-1){
			column.setColumnType(ColumnModel.COLUMNTYPE_DATE);
			return;
		}
		if(dbtype.equalsIgnoreCase("TEXT")){
			column.setColumnType(ColumnModel.COLUMNTYPE_TEXT);
			return;
		}
		if(dbtype.equalsIgnoreCase("BOOLEAN")){
			column.setColumnType(ColumnModel.COLUMNTYPE_BOOLEAN);
			return;
		}
	}
	
	

}
